<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>数据查询</title>

    <!-- 引入 moment.js 库 -->
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
    <!-- 引入 jQuery 库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入 FileSaver.js 和 xlsx 库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <link rel="stylesheet" href="layui/css/layui.css"/>
    <script src="layui/layui.js"></script>

    <style>
        body {
            background-image: url('../images/img_1.png');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        .container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            width: 1400px;
            max-width: 100%;
            display: flex;
            flex-direction: column;
        }

        .title-container {
            text-align: center;
            margin-bottom: 20px;
        }

        .form-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            margin-bottom: 20px;
        }

        .form-container .layui-form-item {
            margin: 5px 10px;
        }

        .table-container {
            flex: 1;
        }

        .layui-form-label {
            width: 80px;
            color: #333;
            font-weight: 600;
        }

        .layui-input-inline {
            width: 180px;
        }

        .layui-form-mid {
            margin-left: 15px;
            vertical-align: middle;
            line-height: 38px;
        }

        .layui-btn {
            background-color: #009688;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }

        .layui-btn:hover {
            background-color: #00796b;
        }

        .layui-textarea {
            resize: none;
            border-radius: 5px;
            height: 100px;
        }

        .layui-elem-field.layui-field-title legend {
            white-space: pre-wrap;
            font-size: 24px;
            color: #333;
            text-align: center;
        }

        .statistics-container {
            margin-top: 20px;
            font-weight: bold;
            color: #333;
            text-align: center;
        }

        .result-container {
            margin-top: 10px;
            font-weight: bold;
            color: #333;
        }
    </style>
</head>

<body>
<div class="container">
    <div class="title-container">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>成远生产管控平台<br>矿车载量信息查询系统</legend>
        </fieldset>
    </div>

    <div class="form-container">
        <form class="layui-form" lay-filter="form">
            <div class="layui-form-item">
                <label class="layui-form-label">门岗</label>
                <div class="layui-input-inline">
                    <select name="gate" id="gate" lay-verify="gate">
                        <option value="">请选择</option>
                        <option value="门牌1">门牌1</option>
                        <option value="门牌2">门牌2</option>
                        <!-- 可以根据需要添加更多选项 -->
                    </select>
                </div>
                <div class="layui-form-mid">
                    <input type="checkbox" name="useGate" id="useGate" title="使用门岗查询" data-target="gate">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">车牌号</label>
                <div class="layui-input-inline">
                    <input type="text" name="plate" id="plate" autocomplete="off" placeholder="车牌号"
                           class="layui-input" lay-verify="plate">
                </div>
                <div class="layui-form-mid">
                    <input type="checkbox" name="usePlate" id="usePlate" title="使用车牌号查询" data-target="plate">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">施工单位</label>
                <div class="layui-input-inline">
                    <select name="belonging" id="belonging" lay-verify="belonging">
                        <option value="">请选择</option>
                        <option value="施工单位A">施工单位A</option>
                        <option value="施工单位B">施工单位B</option>
                        <option value="施工单位C">施工单位C</option>
                        <!-- 可以根据需要添加更多选项 -->
                    </select>
                </div>
                <div class="layui-form-mid">
                    <input type="checkbox" name="useBelonging" id="useBelonging" title="使用施工单位查询"
                           data-target="belonging">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">开始时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="startTime" id="startTime" autocomplete="off" placeholder="开始时间"
                           class="layui-input" lay-verify="startTime">
                </div>
                <div class="layui-form-mid">
                    <input type="checkbox" name="useStartTime" id="useStartTime" title="使用开始时间查询"
                           data-target="startTime">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="endTime" id="endTime" autocomplete="off" placeholder="结束时间"
                           class="layui-input" lay-verify="endTime">
                </div>
                <div class="layui-form-mid">
                    <input type="checkbox" name="useEndTime" id="useEndTime" title="使用结束时间查询"
                           data-target="endTime">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="form">查询</button>
                    <button class="layui-btn" id="exportBtn">导出Excel</button>
                    <div class="result-container" id="result"></div>
                </div>
            </div>
        </form>
    </div>

    <div class="table-container">
        <table id="dataTable" lay-filter="dataTable"></table>
        <div class="statistics-container" id="statistics"></div>
    </div>
</div>

<script>
    layui.use(['form', 'laydate', 'jquery', 'table', 'laypage'], function () {
        var form = layui.form,
            $ = layui.jquery,
            laydate = layui.laydate,
            table = layui.table,
            laypage = layui.laypage;

        // 初始化日期时间选择器
        laydate.render({
            elem: '#startTime',
            type: 'datetime', // 支持时分秒选择
            done: function (value, date) {
                if (value) {
                    console.log('开始时间选择完成:', value);
                }
            }
        });
        laydate.render({
            elem: '#endTime',
            type: 'datetime', // 支持时分秒选择
            done: function (value, date) {
                if (value) {
                    console.log('结束时间选择完成:', value);
                }
            }
        });

        form.render();

        // 自定义验证规则
        form.verify({
            plate: function (value, item) {
                if ($('#usePlate').is(':checked') && !value) {
                    return '车牌号不能为空';
                }
                // 车牌号模式验证，例如 "京A66666"
                var platePattern = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{5}$/;
                if ($('#usePlate').is(':checked') && !platePattern.test(value)) {
                    return '车牌号格式不正确，例如：京A66666';
                }
            },
            belonging: function (value, item) {
                if ($('#useBelonging').is(':checked') && value === '') {
                    return '请选择施工单位';
                }
            },
            startTime: function (value, item) {
                if ($('#useStartTime').is(':checked') && !value) {
                    return '开始时间不能为空';
                }
            },
            endTime: function (value, item) {
                if ($('#useEndTime').is(':checked') && !value) {
                    return '结束时间不能为空';
                }
                var startTime = $('#startTime').val();
                if ($('#useStartTime').is(':checked') && $('#useEndTime').is(':checked') && moment(value) < moment(startTime)) {
                    return '结束时间不能早于开始时间';
                }
            },
            gate: function (value, item) {
                if ($('#useGate').is(':checked') && value === '') {
                    return '请选择门岗';
                }
            }
        });

        // 初始化表格
        var tableIns = table.render({
            elem: '#dataTable',
            cols: [[
                { field: 'id', title: '序号', width: 80 },
                { field: 'uuid', title: '唯一标识符', minWidth: 80 },
                { field: 'gate', title: '门岗', width: 100 },
                { field: 'belonging', title: '施工单位', width: 100 },
                { field: 'plate', title: '车牌号', minWidth: 120 },
                { field: 'time', title: '时间', width: 120 },
                { field: 'material', title: '材料', width: 90 },
                { field: 'density', title: '密度', width: 90 },
                { field: 'volume', title: '体积', width: 90 },
                { field: 'weight', title: '重量', width: 90 },
                { field: 'scan', title: '扫描状态', minWidth: 90 },
                { field: 'status', title: '同步状态', width: 90 },
                { title: '操作', width: 120, toolbar: '#barDemo' } // 添加操作列

            ]],
            page: true,
            limit: 10,
            limits: [10, 20, 30],
            response: {
                statusCode: 0 // 0 代表成功
            },
            done: function (res, curr, count) {
                // 显示统计结果
                var totalWeight = res.totalWeight !== undefined ? res.totalWeight : 0;
                var totalVolume = res.totalVolume !== undefined ? res.totalVolume : 0;

                $('#statistics').html("合计: " + totalWeight.toFixed(2) + ' 吨, ' + totalVolume.toFixed(2) + ' 立方米');
            },
            error: function (res) {
                layer.msg('查询失败');
            }
        });

        // 监听工具条
        table.on('tool(dataTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                // 弹出编辑窗口
                layer.open({
                    type: 1, // 类型为页面层
                    title: '编辑数据',
                    area: ['500px', '400px'], // 宽高
                    content: `
                <form class="layui-form" style="padding: 20px;" id="editForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">门岗</label>
                        <div class="layui-input-block">
                            <input type="text" name="gate" value="${data.gate}" autocomplete="off" placeholder="请输入门岗" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">施工单位</label>
                        <div class="layui-input-block">
                            <input type="text" name="belonging" value="${data.belonging}" autocomplete="off" placeholder="请输入施工单位" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">车牌号</label>
                        <div class="layui-input-block">
                            <input type="text" name="plate" value="${data.plate}" autocomplete="off" placeholder="请输入车牌号" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">时间</label>
                        <div class="layui-input-block">
                            <input type="text" name="time" value="${data.time}" autocomplete="off" placeholder="请输入时间" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">材料</label>
                        <div class="layui-input-block">
                            <input type="text" name="material" value="${data.material}" autocomplete="off" placeholder="请输入材料" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密度</label>
                        <div class="layui-input-block">
                            <input type="text" name="density" value="${data.density}" autocomplete="off" placeholder="请输入密度" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">体积</label>
                        <div class="layui-input-block">
                            <input type="text" name="volume" value="${data.volume}" autocomplete="off" placeholder="请输入体积" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">重量</label>
                        <div class="layui-input-block">
                            <input type="text" name="weight" value="${data.weight}" autocomplete="off" placeholder="请输入重量" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">扫描状态</label>
                        <div class="layui-input-block">
                            <input type="text" name="scan" value="${data.scan}" autocomplete="off" placeholder="请输入扫描状态" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">同步状态</label>
                        <div class="layui-input-block">
                            <input type="text" name="status" value="${data.status}" autocomplete="off" placeholder="请输入同步状态" class="layui-input">
                        </div>
                    </div>
                    <input type="hidden" name="id" value="${data.id}">
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="saveEdit">保存</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                        </div>
                    </div>
                </form>
            `,
                    success: function (layero, index) {
                        // 手动实现重置功能
                        $('#resetBtn').on('click', function () {
                            $('#editForm')[0].reset(); // 清空表单
                        });

                        // 监听保存按钮的提交事件
                        form.on('submit(saveEdit)', function (formData) {
                            var updatedData = formData.field;

                            // 将字符串类型的数字字段转换为数字类型
                            updatedData.density = parseFloat(updatedData.density);
                            updatedData.volume = parseFloat(updatedData.volume);
                            updatedData.weight = parseFloat(updatedData.weight);
                            updatedData.scan = parseInt(updatedData.scan);
                            updatedData.status = parseInt(updatedData.status);

                            // 打印发送的数据
                            console.log('Sending Data:', JSON.stringify({ id: data.id, ...updatedData }));

                            // 发送保存请求
                            $.ajax({
                                type: 'POST',
                                url: 'http://59.110.144.74/truckRecord/update',
                                data: JSON.stringify(updatedData),
                                contentType: 'application/json',
                                success: function (res) {
                                    console.log('更新成功:', res);
                                    layer.msg('更新成功');
                                    layer.close(index); // 关闭弹出窗口
                                    tableIns.reload(); // 刷新表格
                                },
                                error: function (xhr, status, error) {
                                    console.error('Error Status:', xhr.status);
                                    console.error('Error Response:', xhr.responseText);
                                    layer.msg('更新失败: ' + xhr.responseText);
                                }
                            });

                            return false; // 阻止表单默认提交行为
                        });
                    }
                });
            }
        });



        // 全局变量用于存储查询到的数据
        var globalQueryData = [];

        // 定义加载数据的函数
        function loadData(queryData) {
            var baseUrl = 'http://59.110.144.74:8080';
            baseUrl='http://59.110.144.74:8080';
            var url = baseUrl + '/truckRecord/truckRecords';

            console.log('Query Data:', queryData); // 添加日志

            $.ajax({
                type: 'GET',
                url: url,
                data: queryData,
                dataType: 'json',
                success: function (res) {
                    console.log('Response:', res);
                    // 更新全局变量
                    globalQueryData = res.data;
                    // 更新表格数据
                    tableIns.reload({
                        data: res.data,
                        page: {
                            curr: 1
                        }
                    });

                    // 显示统计结果
                    var totalWeight = res.totalWeight !== undefined ? res.totalWeight : 0;
                    var totalVolume = res.totalVolume !== undefined ? res.totalVolume : 0;

                    $('#statistics').html("合计: " + totalWeight.toFixed(2) + ' 吨, ' + totalVolume.toFixed(2) + ' 立方米');
                },
                error: function (xhr, status, error) {
                    console.error(error);
                    layer.msg('查询失败');
                }
            });
        }

        // 页面加载完成后自动加载数据
        $(document).ready(function () {
            var isAdmin = sessionStorage.getItem('isAdmin') === 'true';

            // $('#exportBtn').hide();


            loadData({});
        });

        // 监听表单提交
        form.on('submit(form)', function (data) {
            console.log(data);
            var formData = data.field;
            var queryData = {};

            if (formData.usePlate === 'on' && formData.plate) {
                queryData.plate = formData.plate;
            }
            if (formData.useGate === 'on' && formData.gate) {
                queryData.gate = formData.gate; // 不再转换为整数，因为选项值是字符串
            }
            if (formData.useBelonging === 'on' && formData.belonging) {
                queryData.belonging = formData.belonging;
            }
            if (formData.useStartTime === 'on' && formData.startTime) {
                queryData.startTime = formData.startTime;
            }
            if (formData.useEndTime === 'on' && formData.endTime) {
                queryData.endTime = formData.endTime;
            }

            console.log(queryData);

            // 加载数据
            loadData(queryData);

            return false; // 阻止表单默认提交行为
        });

        // 定义导出Excel的函数
        function exportToExcel(data, filename) {
            try {
                // 定义列名映射对象
                var columnMapping = {
                    id: '序号',
                    uuid: '唯一标识符',
                    gate: '门岗',
                    belonging: '施工单位',
                    plate: '车牌号',
                    time: '时间',
                    material: '材料',
                    density: '密度',
                    volume: '体积',
                    weight: '重量',
                    scan: '扫描状态',
                    status: '同步状态'
                };

                // 转换数据
                var transformedData = data.map(function (item) {
                    var transformedItem = {};
                    for (var key in item) {
                        if (columnMapping[key]) {
                            transformedItem[columnMapping[key]] = item[key];
                        } else {
                            transformedItem[key] = item[key];
                        }
                    }
                    return transformedItem;
                });

                // 创建工作簿
                var workbook = XLSX.utils.book_new();
                // 将数据转换为工作表
                var worksheet = XLSX.utils.json_to_sheet(transformedData);
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                // 生成Excel文件
                var excelBuffer = XLSX.write(workbook, {
                    bookType: 'xlsx',
                    type: 'array'
                });
                // 创建Blob对象
                var blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
                // 保存文件
                saveAs(blob, filename + '.xlsx');
                layer.msg('导出成功');
            } catch (error) {
                console.error(error);
                layer.msg('导出失败: ' + error.message);
            }
        }

        // 绑定导出按钮的点击事件
        $('#exportBtn').on('click', function () {
            if (globalQueryData.length === 0) {
                layer.msg('没有数据可导出');
                return;
            }

            // 弹出保存文件对话框，让用户输入文件名
            var filename = prompt('请输入要保存的文件名（不包含扩展名）', '矿车载量信息');
            if (filename === null) {
                // 用户取消了输入
                return;
            }

            // 去除文件名中的非法字符
            filename = filename.replace(/[\\/*?:"<>|]/g, '');

            // 调用导出函数
            exportToExcel(globalQueryData, filename);
        });
    });
</script>

<!-- 添加操作列模板 -->
<script type="text/html" id="barDemo">        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>

</script>


</body>

</html>
